package demo02;

import demo01.JDBCUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.*;
import java.util.Scanner;
public class JDBCTest {
    public static void main(String[] args) {

        try {
            //捕获异常

            findAll();
            //增加
            insertInfo();
            //修改
            deleteInfo();
            //删除
            upDateInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void upDateInfo() {
    }

    private static void deleteInfo() {
    }

    private static  void insertInfo() throws Exception {
       Scanner sc=new Scanner(System.in);
       System.out.println("eid：");
       String eid=sc.next();
       System.out.println("name：");
       String name=sc.next();
       System.out.println("age：");
       int age=sc.nextInt();
       System.out.println("department：");
       String department=sc.next();
       System.out.println("salary：");
       double salary=sc.nextDouble();

        Connection conn = JDBCUtil.getConn();
        //执行插入
        Statement stmt = conn.createStatement();
       // String sql = "insert into employee(eid,name,age,department,salary) values('0003','张三',20,'IT',5000)";
        //stmt.executeUpdate(sql);
        String sql = "insert into employee(eid,name,age,department,salary) values(?,?,?,?,?)";
        PreparedStatement ps=conn.prepareStatement(sql);//预编译sql语句，防止sql注入
        ps.setString(1,eid);
        ps.setString(2,name);
        ps.setInt(3,age);
        ps.setString(4,department);
        ps.setDouble(5,salary);
        int count = ps.executeUpdate();
        if(count>0)
        {
            System.out.println("插入成功");
        }else{
            System.out.println("插入失败");
        }
        //释放内存
        JDBCUtil.close(stmt,conn);
    }

    private static void findAll() throws Exception {
        Connection conn = JDBCUtil.getConn();
        //执行查找
        Statement stml = conn.createStatement();
        String sql = "select * from employee";
        ResultSet rs = stml.executeQuery(sql);
        while (rs.next()) {
            int id=rs.getInt("id");
            String eid=rs.getString("eid");
            String name=rs.getString("name");
            int age=rs.getInt("age");
            String department=rs.getString("department");
             double salary=rs.getDouble("salary");
             System.out.println(id+" "+eid+" "+name+" "+age+" "+department+" "+salary);
        }
        //释放内存
        JDBCUtil.close(rs,stml,conn);
    }
}
